package com.ruoyi.web.controller.cryptocard;

import java.math.BigDecimal;
import java.time.Year;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.TimeStampUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.system.domain.reseller.VsDramasReseller;
import com.ruoyi.system.domain.reseller.VsDramasResellerBind;
import com.ruoyi.system.domain.reseller.VsDramasResellerOrder;
import com.ruoyi.system.domain.usable.VsDramasUsable;
import com.ruoyi.system.domain.usable.VsDramasUsableOrder;
import com.ruoyi.system.domain.user.VsDramasUserCryptocard;
import com.ruoyi.system.domain.video.VsLang;
import com.ruoyi.system.domain.vip.VsDramasVip;
import com.ruoyi.system.domain.vip.VsDramasVipOrder;
import com.ruoyi.system.mapper.reseller.VsDramasResellerOrderMapper;
import com.ruoyi.system.mapper.usable.VsDramasUsableOrderMapper;
import com.ruoyi.system.mapper.vip.VsDramasVipOrderMapper;
import com.ruoyi.system.service.reseller.IVsDramasResellerBindService;
import com.ruoyi.system.service.reseller.IVsDramasResellerOrderService;
import com.ruoyi.system.service.reseller.IVsDramasResellerService;
import com.ruoyi.system.service.usable.IVsDramasUsableOrderService;
import com.ruoyi.system.service.usable.IVsDramasUsableService;
import com.ruoyi.system.service.user.IVsDramasUserCryptocardService;
import com.ruoyi.system.service.video.IVsLangService;
import com.ruoyi.system.service.vip.IVsDramasVipOrderService;
import com.ruoyi.system.service.vip.IVsDramasVipService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.cryptocard.VsDramasCryptocard;
import com.ruoyi.system.service.cryptocard.IVsDramasCryptocardService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
/**
 * This file is part of 南阳迈特网络科技有限公司.
 * @company  南阳迈特网络科技有限公司
 * @link     https://www.nymaite.com
 * @document https://product.nymaite.cn
 * @contact  service@nymaite.com
 * @author nymaite
 */
/**
 * 卡密Controller
 * 
 * @author zzx
 * @date 2024-04-27
 */
@Api(tags = "卡密管理")
@RestController
@RequestMapping("/cryptocard/cryptocard")
public class VsDramasCryptocardController extends BaseController
{
    @Autowired
    private IVsDramasCryptocardService vsDramasCryptocardService;

    @Autowired
    private IVsLangService vsLangService;

    @Autowired
    private IVsDramasVipService vsDramasVipService;

    @Autowired
    private VsDramasVipOrderMapper vsDramasVipOrderService;

    @Autowired
    private IVsDramasResellerService vsDramasResellerService;

    @Autowired
    private VsDramasResellerOrderMapper vsDramasResellerOrderService;

    @Autowired
    private IVsDramasUsableService vsDramasUsableService;

    @Autowired
    private VsDramasUsableOrderMapper vsDramasUsableOrderService;

    @Autowired
    private IVsDramasUserCryptocardService vsDramasUserCryptocardService;

    @Autowired
    private IVsDramasResellerBindService vsDramasResellerBindService;

    /**
     * 查询卡密列表
     */
//    @ApiOperation("查询卡密列表")
    @GetMapping("/list")
    public TableDataInfo list(VsDramasCryptocard vsDramasCryptocard)
    {
        startPage();
        List<VsDramasCryptocard> list = vsDramasCryptocardService.selectVsDramasCryptocardList(vsDramasCryptocard);
        return getDataTable(list);
    }

    /**
     * 导出卡密列表
     */
//    @ApiOperation("导出卡密数据")
    @Log(title = "卡密", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VsDramasCryptocard vsDramasCryptocard)
    {
        List<VsDramasCryptocard> list = vsDramasCryptocardService.selectVsDramasCryptocardList(vsDramasCryptocard);
        ExcelUtil<VsDramasCryptocard> util = new ExcelUtil<VsDramasCryptocard>(VsDramasCryptocard.class);
        util.exportExcel(response, list, "卡密数据");
    }

    /**
     * 获取卡密详细信息
     */
//    @ApiOperation("获取卡密详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(vsDramasCryptocardService.selectVsDramasCryptocardById(id));
    }

    /**
     * 新增卡密
     */
//    @ApiOperation("新增卡密")
    @Log(title = "卡密", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VsDramasCryptocard vsDramasCryptocard)
    {
        return toAjax(vsDramasCryptocardService.insertVsDramasCryptocard(vsDramasCryptocard));
    }

    /**
     * 修改卡密
     */
//    @ApiOperation("修改卡密")
    @Log(title = "卡密", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VsDramasCryptocard vsDramasCryptocard)
    {
        return toAjax(vsDramasCryptocardService.updateVsDramasCryptocard(vsDramasCryptocard));
    }

    /**
     * 删除卡密
     */
//    @ApiOperation("删除卡密")
    @Log(title = "卡密", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(vsDramasCryptocardService.deleteVsDramasCryptocardByIds(ids));
    }

    @PostMapping("/exchange")
    public AjaxResult exchange(@RequestBody VsDramasCryptocard vsDramasCryptocard, HttpServletRequest request) {
        if (getLoginUser().getVsUser() == null) {
            return error();
        }
        if ("guest".equals(getLoginUser().getVsUser().getMode())) {
            return error();
        }
        long l = System.currentTimeMillis();
        VsDramasCryptocard isCryptocard = new VsDramasCryptocard();
        isCryptocard.setPwd(vsDramasCryptocard.getPwd());
        isCryptocard.setExchangeTime(l);
        List<VsDramasCryptocard> cryptocards = vsDramasCryptocardService.selectVsDramasCryptocardInfo(isCryptocard);
        if (cryptocards.isEmpty()) {
            return error();
        }
        vsDramasCryptocard.setUserId(getLoginUser().getVsUser().getId());
        int i = vsDramasCryptocardService.exchange(vsDramasCryptocard);
        if (i > 0) {
            VsDramasCryptocard card = new VsDramasCryptocard();
            card.setPwd(vsDramasCryptocard.getPwd());
            List<VsDramasCryptocard> list = vsDramasCryptocardService.selectVsDramasCryptocardList(card);
            VsLang lang = vsLangService.selectVsLangById(request.getHeader("Lang-Id"));
            VsDramasCryptocard cryptocard = vsDramasCryptocardService.selectVsDramasCryptocardById(list.get(0).getId());
            VsDramasVip vsDramasVip = new VsDramasVip();
            VsDramasUsable vsDramasUsable = new VsDramasUsable();
            VsDramasReseller vsDramasReseller = new VsDramasReseller();
            if ("vip".equals(cryptocard.getType())) {
                vsDramasVip = vsDramasVipService.selectVsDramasVipById(Math.toIntExact(cryptocard.getItemId()));
                VsDramasVipOrder vipOrder = new VsDramasVipOrder();
                vipOrder.setVipId(vsDramasVip.getId());
                vipOrder.setLangId(vsDramasVip.getLangId());
                String s = "A" + l + IdUtils.fastSimpleUUID();
                vipOrder.setOrderSn(s);
                vipOrder.setUserId(Math.toIntExact(getLoginUser().getVsUser().getId()));
                if ("周".equals(vsDramasVip.getType())) {
                    int num = Integer.parseInt(vsDramasVip.getNum());
                    int result = 7 * num;
                    long timeStampByDate = TimeStampUtils.getTimeStampByDate(result);
                    vipOrder.setTimes(timeStampByDate);
                } else if ("月".equals(vsDramasVip.getType())) {
                    int num = Integer.parseInt(vsDramasVip.getNum());
                    int result = 30 * num;
                    long timeStampByDate = TimeStampUtils.getTimeStampByDate(result);
                    vipOrder.setTimes(timeStampByDate);
                } else if ("年".equals(vsDramasVip.getType())) {
                    int num = Integer.parseInt(vsDramasVip.getNum());
                    // 获取当前年份
                    int currentYear = Year.now().getValue();
                    // 由于每年的天数取决于是否是闰年，可以通过以下方式计算
                    boolean isLeapYear = Year.isLeap(currentYear);
                    int daysInYear = isLeapYear ? 366 : 365;
                    int result = daysInYear * num;
                    long timeStampByDate = TimeStampUtils.getTimeStampByDate(result);
                    vipOrder.setTimes(timeStampByDate);
                }
                vipOrder.setStatus(2L);
                vipOrder.setTotalFee(vsDramasVip.getPrice());
                vipOrder.setPayFee(BigDecimal.ZERO);
                vipOrder.setCurrency(lang.getCurrency());
                vipOrder.setRemark("卡密兑换");
                vipOrder.setPayType("cryptocard");
                vipOrder.setCreatetime(l);
                vipOrder.setUpdatetime(l);
                int order = vsDramasVipOrderService.insertVsDramasVipOrder(vipOrder);
                if (order > 0) {
                    VsDramasUserCryptocard vsDramasUserCryptocard = new VsDramasUserCryptocard();
                    vsDramasUserCryptocard.setUserId(getLoginUser().getVsUser().getId());
                    vsDramasUserCryptocard.setCryptocardId(Long.valueOf(list.get(0).getId()));
                    vsDramasUserCryptocard.setType("vip");
                    vsDramasUserCryptocard.setOrderId(Long.valueOf(vipOrder.getId()));
                    vsDramasUserCryptocard.setCreatetime(l);
                    int dramasUserCryptocard = vsDramasUserCryptocardService.insertVsDramasUserCryptocard(vsDramasUserCryptocard);
                    if (dramasUserCryptocard == 0) {
                        return error();
                    }
                    return success();
                }
            } else if ("reseller".equals(cryptocard.getType())) {
                vsDramasReseller = vsDramasResellerService.selectVsDramasResellerById(Math.toIntExact(cryptocard.getItemId()));
                VsDramasResellerOrder resellerOrder = new VsDramasResellerOrder();
                resellerOrder.setResellerId(vsDramasReseller.getId());
                String s = "R" + l + IdUtils.fastSimpleUUID();
                resellerOrder.setOrderSn(s);
                resellerOrder.setUserId(Math.toIntExact(getLoginUser().getVsUser().getId()));
                resellerOrder.setLangId(vsDramasReseller.getLangId());
                resellerOrder.setTimes(vsDramasReseller.getExpire());
                resellerOrder.setStatus(2);
                resellerOrder.setTotalFee(vsDramasReseller.getPrice());
                resellerOrder.setPayFee(BigDecimal.ZERO);
                resellerOrder.setCurrency(lang.getCurrency());
                resellerOrder.setRemark("卡密兑换");
                resellerOrder.setPayType("cryptocard");
                resellerOrder.setCreatetime(l);
                resellerOrder.setUpdatetime(l);
                int order = vsDramasResellerOrderService.insertVsDramasResellerOrder(resellerOrder);
                if (order == 0) {
                    return error();
                }
                int resellerInfo = resellerOrder(s);
                if (resellerInfo == 0) {
                    return error();
                }
                VsDramasUserCryptocard vsDramasUserCryptocard = new VsDramasUserCryptocard();
                vsDramasUserCryptocard.setUserId(getLoginUser().getVsUser().getId());
                vsDramasUserCryptocard.setCryptocardId(Long.valueOf(list.get(0).getId()));
                vsDramasUserCryptocard.setType("reseller");
                vsDramasUserCryptocard.setOrderId(Long.valueOf(resellerOrder.getId()));
                vsDramasUserCryptocard.setCreatetime(l);
                int dramasUserCryptocard = vsDramasUserCryptocardService.insertVsDramasUserCryptocard(vsDramasUserCryptocard);
                if (dramasUserCryptocard == 0) {
                    return error();
                }
                return success();
            } else if ("usable".equals(cryptocard.getType())) {
                vsDramasUsable = vsDramasUsableService.selectVsDramasUsableById(Math.toIntExact(cryptocard.getItemId()));
                VsDramasUsableOrder usableOrder = new VsDramasUsableOrder();
                usableOrder.setUsableId(vsDramasUsable.getId());
                String s = "U" + l + IdUtils.fastSimpleUUID();
                usableOrder.setOrderSn(s);
                usableOrder.setUserId(Math.toIntExact(getLoginUser().getVsUser().getId()));
                usableOrder.setLangId(vsDramasUsable.getLangId());
                usableOrder.setUsable(vsDramasUsable.getUsable());
                usableOrder.setStatus(2);
                usableOrder.setTotalFee(vsDramasUsable.getPrice());
                usableOrder.setPayFee(BigDecimal.ZERO);
                usableOrder.setCurrency(lang.getCurrency());
                usableOrder.setRemark("卡密兑换");
                usableOrder.setPayType("cryptocard");
                usableOrder.setCreatetime(l);
                usableOrder.setUpdatetime(l);
                int order = vsDramasUsableOrderService.insertVsDramasUsableOrder(usableOrder);
                if (order == 0) {
                    return error();
                }
                VsDramasUserCryptocard vsDramasUserCryptocard = new VsDramasUserCryptocard();
                vsDramasUserCryptocard.setUserId(getLoginUser().getVsUser().getId());
                vsDramasUserCryptocard.setCryptocardId(Long.valueOf(list.get(0).getId()));
                vsDramasUserCryptocard.setType("usable");
                vsDramasUserCryptocard.setOrderId(usableOrder.getId());
                vsDramasUserCryptocard.setCreatetime(l);
                int dramasUserCryptocard = vsDramasUserCryptocardService.insertVsDramasUserCryptocard(vsDramasUserCryptocard);
                if (dramasUserCryptocard == 0) {
                    return error();
                }
                return success();
            }

        }
        return error();
    }

    private int resellerOrder(String orderSn) {
        VsDramasResellerOrder userOrder = new VsDramasResellerOrder();
        userOrder.setOrderSn(orderSn);
        List<VsDramasResellerOrder> orders = vsDramasResellerOrderService.selectVsDramasResellerOrderList(userOrder);
        if (orders.size() > 0) {
            VsDramasReseller reseller = vsDramasResellerService.selectVsDramasResellerById(orders.get(0).getResellerId());
            VsDramasResellerBind resellerBind = new VsDramasResellerBind();
            resellerBind.setResellerId(Long.valueOf(reseller.getId()));
            resellerBind.setUserId(SecurityUtils.getLoginUser().getVsUser().getId());
            resellerBind.setLevel(Long.valueOf(reseller.getLevel()));
            resellerBind.setExpiretime(orders.get(0).getTimes());
            String s = JSON.toJSONString(reseller);
            resellerBind.setResellerJson(s);
            resellerBind.setCreatetime(System.currentTimeMillis());
            resellerBind.setUpdatetime(System.currentTimeMillis());
            VsDramasResellerBind isBind = new VsDramasResellerBind();
            isBind.setUserId(SecurityUtils.getLoginUser().getVsUser().getId());
            List<VsDramasResellerBind> resellerBinds = vsDramasResellerBindService.selectVsDramasResellerBindList(isBind);
            // 如果当前用户以前充值过分销商，那就覆盖之前的分销商相关权益信息，否则就新增该用户的分销商相关权益信息
            if (resellerBinds.size() > 0) {
                return vsDramasResellerBindService.updateUserResellerBind(resellerBind);
            }
            return vsDramasResellerBindService.insertVsDramasResellerBind(resellerBind);
        }
        return 0;
    }

}
